import {
    Participant,
    RemoteParticipant,
    RemoteTrack,
    RemoteTrackPublication,
    Room,
    RoomEvent,
    Track,
    ParticipantEvent,
    TrackPublication,
    VideoPresets
} from 'livekit-client';
import configs from '@/config/config'
let wsURL = configs.livekit_host// wss
let timer = null
let count = 0
let room = null
let init = true
import store from '@/store'

// import v3layer from '@/components/v3layer/index'
//  房间号， readyCallback 房间准备回调， localReadyCallback 本地用户准备回调， remoteReadyCallback 远端用户准备回调
export const livekit_main = async (
    data, // token 数据
    readyCallback, // 房间准备回调，
    localReadyCallback, // 本地用户准备回调，
    participantConnectedCallback, // 远端用户连接回调
    remoteReadyCallback, //远端用户准备回调
    trackMutedCallback, // 远端用户禁音回调
    participantDisconnectedCallback, // 远端用户断开回调
    activeSpeakerCallback, // 主讲人回调
    localTrackUnpublishedCallback,//视频/共享屏幕关闭
    roomMetadataChanged, // 房间元数据改变
    dataReceivedCallback,
	roomConnectedCallBack // 房间准备已就绪
) => {
    room = new Room({ // 创建房间
        // automatically manage subscribed video quality
        adaptiveStream: true,// 自动管理订阅视频质量

        // optimize publishing bandwidth and CPU for published tracks
        dynacast: true, // 动态转码

        // enable simulcast for published tracks
        simulcast: true,// 启用多路复用

        // enable simulcast for subscribed tracks
        // simulcast: true,

        // default capture settings
        // videoCaptureDefaults: { // 视频采集设置
        //     resolution: VideoPresets.h720.resolution,
        // },
        // audioCaptureDefaults: { // 音频采集设置
        //     sampleRate: 48000,
        //     sampleSize: 16,
        //     channels: 1,
        // },
    });
    room.prepareConnection(wsURL, data.roomToken); //预热调用
    // 事件监听
    room
        .on(RoomEvent.ParticipantConnected, handleParticipantConnected) // 有人加入房间
        .on(RoomEvent.TrackSubscribed, handleTrackSubscribed) // 订阅成功
        .on(RoomEvent.TrackPublished, handleTrackPublished) //  发布成功
        .on(RoomEvent.LocalTrackPublished, handleLocalTrackPublished) // 本地发布成功
        .on(RoomEvent.TrackUnsubscribed, handleTrackUnsubscribed)// 取消订阅
        .on(RoomEvent.TrackMuted, handleTrackMuted) //禁音
        .on(RoomEvent.TrackUnmuted, handleTrackUnmuted) //取消禁音
        .on(RoomEvent.ActiveSpeakersChanged, handleActiveSpeakerChange) // 主讲人改变
        .on(RoomEvent.IsSpeakingChanged, handleIsSpeakingChanged) // 主讲人改变
        .on(RoomEvent.TrackStreamStateChanged, handleTrackStreamStateChanged)
        .on(RoomEvent.ParticipantDisconnected, handleParticipantDisconnected)// 有人离开
        .on(RoomEvent.Disconnected, handleDisconnect)// 断开连接
        .on(RoomEvent.RoomMetadataChanged, handleRoomMetadataChanged) // 房间信息改变
        .on(RoomEvent.ParticipantMetadataChanged, handleParticipantMetadataChanged) // 用户信息改变
        .on(RoomEvent.DataReceived, handleDataReceived) // 监听发送数据
        .on(RoomEvent.LocalTrackUnpublished, handleLocalTrackUnpublished) // 取消发布
		.on(RoomEvent.Connected, handleConnected) // 房间准备已就绪

    // connect to room
    await room.connect(wsURL, data.roomToken); // 连接房间
    // const media = await room.localParticipant.enableCameraAndMicrophone(true)// 打开麦克风以及摄像头
    // console.log(media)
    try {
        console.log('传入数据')
        console.log(data)
        await room.localParticipant.setMicrophoneEnabled(data.microphone)
        await room.localParticipant.setCameraEnabled(data.camera, { facingMode: 'environment' });
    } catch (error) {
        // v3layer.notify({
        //     content: '设备被占用或者缺少设备', icon: 'warning', shade: true, opacity: 0, layerStyle: 'background:#fef0f0;border-radius:6px;color:#f56c6c;margin-top:10px;'
        // })
        await room.localParticipant.setMicrophoneEnabled(data.microphone);
    }
    //  await room.localParticipant.setCameraEnabled(true);// 打开摄像头
    //  await room.localParticipant.setMicrophoneEnabled(true);// 打开语音
    console.log('房间链接已就绪', room);
    init = false
    readyCallback && readyCallback(room);
    startTime(data)
    function handleTrackSubscribed(
        track = RemoteTrack,
        publication = RemoteTrackPublication,
        participant = RemoteParticipant,
    ) { //LocalParticipant 第一次进入房间，已经进来过的人会依次返回, 或者是其他人加入房间返回
        console.log('有人连接成功回调', participant.name)
        !init && remoteReadyCallback && remoteReadyCallback(track, publication, participant)
    }
    function handleParticipantConnected(participant = RemoteParticipant) { // 有人加入房间监听
        console.log('有人加入房间', participant);
        participantConnectedCallback && participantConnectedCallback(participant)
        // participant
        //     .on(ParticipantEvent.TrackMuted,(publication = TrackPublication) => {
        //         handleTrackMuted(publication, participant)
        //     } )
        //     .on(ParticipantEvent.TrackUnmuted, (publication = TrackPublication) => {
        //         handleTrackUnmuted(publication, participant)
        //     } )
        //     .on(ParticipantEvent.IsSpeakingChanged,() => {
        //         handleIsSpeakingChanged(participant)
        //     } )
            // .on(ParticipantEvent.ConnectionQualityChanged, () => {
            //     renderParticipant(participant);
            // });
    }

    function handleTrackPublished(
        publication = LocalTrackPublication,
        participant = LocalParticipant,
    ) { //有人加入并且音频视频发布成功
        console.log('有人加入发布媒体', participant.name, publication);
        // trackPublishedCallback && trackPublishedCallback(publication, participant)
    }

    //本地自己链接成功后返回自己的信息和媒体信息
    function handleLocalTrackPublished(
        publication = LocalTrackPublication,
        participant = LocalParticipant,
    ) {
        // when local tracks are published, update UI to show them
        console.log('本地创建发布成功', publication.track.kind);
        localReadyCallback && localReadyCallback(publication, participant)

    }
    function handleRoomMetadataChanged(metadata) { // 监听房间信息改变 用来控制房间是否禁言
        console.log('room metadata changed', metadata);
        roomMetadataChanged && roomMetadataChanged(metadata);
    }
    function handleParticipantMetadataChanged(
        participant = RemoteParticipant,
        metadata = ParticipantMetadata,
    ) {
        console.log('participant metadata changed', participant, metadata);
    }
    function handleTrackUnsubscribed(
        track = RemoteTrack,
        publication = RemoteTrackPublication,
        participant = RemoteParticipant,
    ) { // 视频共享左面取消监听
        // remove tracks from all attached elements
        console.log('track unsubscribed', track, publication, participant);
        localTrackUnpublishedCallback && localTrackUnpublishedCallback(publication, participant);
        // track.detach();
    }
    function handleLocalTrackUnpublished(
        publication = LocalTrackPublication,
        participant = LocalParticipant,
    ) { // 结束共享/取消视频
        // when local tracks are ended, update UI to remove them from rendering
        console.log('local track unpublished', publication, participant);
        // publication.track.detach();
        localTrackUnpublishedCallback && localTrackUnpublishedCallback(publication, participant)
    }
    function handleActiveSpeakerChange(speakers) { // 监听说话人音频波动
        // console.log('active speakers changed', speakers);
        // show UI indicators when participant is speaking
        activeSpeakerCallback && activeSpeakerCallback(speakers)
    }
    function handleIsSpeakingChanged(participant) {
        console.log('is speaking changed', participant);
        // isSpeakingCallback && isSpeakingCallback(isSpeaking, participant)
    }
    function handleDisconnect() {
        console.log('room has been disconnected');
        console.log('disconnected from room');
    }
    function handleTrackStreamStateChanged(
        track = RemoteTrack,
        stream = MediaStreamTrack,
        publication = RemoteTrackPublication,
        participant = RemoteParticipant,
        streamState = Track.StreamState,
    ) {
        console.log('track stream state changed', track, stream, publication, participant, streamState);
    }
    function handleTrackMuted( // 禁言
        publication = RemoteTrackPublication,
        participant = RemoteParticipant,
    ) {
        console.log('track muted', publication, participant);
        trackMutedCallback && trackMutedCallback(publication, participant)
    }
    function handleTrackUnmuted( //取消禁言
        publication = RemoteTrackPublication,
        participant = RemoteParticipant,
    ) {
        console.log('track unmuted', publication, participant);
        trackMutedCallback && trackMutedCallback(publication, participant)
    }
    function handleDataReceived( // 监听发送数据
        dataPacket = DataPacket
    ) {
        // console.log('data received', dataPacket);
        dataReceivedCallback && dataReceivedCallback(dataPacket)
    }
	// 房间准备已就绪
	function handleConnected(){
		roomConnectedCallBack && roomConnectedCallBack()
	}
    function handleParticipantDisconnected(participant = RemoteParticipant) {
        //有人离开房间
        console.log('participant disconnected', participant);
        participantDisconnectedCallback && participantDisconnectedCallback(participant)
    }

}
export const stopMeetting = async (callBack) => { // 断开链接
    await room.disconnect(true)
    count = 0
    room = null
    clearInterval(timer);
    store.commit('user/SET_ONLINE', false)
    timer = null
    init = true
    callBack && callBack()
}
export const closeMeettingCamera = async (callBack) => { // 关闭视频
    const isCameraEnabled = room.localParticipant.isCameraEnabled
    await room.localParticipant.setCameraEnabled(!isCameraEnabled, { facingMode: 'environment' })
    callBack && callBack(!isCameraEnabled)
}
export const closeMeettingMic = async ( type = 2, callBack) => { // 关闭音频
    const isMicrophoneEnabled = room.localParticipant.isMicrophoneEnabled
    if(type == 0) await room.localParticipant.setMicrophoneEnabled(false),  callBack && callBack(false) // 禁言
    if(type == 1) await room.localParticipant.setMicrophoneEnabled(true),  callBack && callBack(true)// 打开禁言
    if(type == 2) await room.localParticipant.setMicrophoneEnabled(!isMicrophoneEnabled), callBack && callBack(!isMicrophoneEnabled) // 打开关闭麦克风
   
}
export const shareScreen = async (callBack) => { // 共享屏幕
    const isScreenShareEnabled = room.localParticipant.isScreenShareEnabled
    await room.localParticipant.setScreenShareEnabled(!isScreenShareEnabled)
    callBack && callBack(!isScreenShareEnabled)
}

let startTime = function (data) {
    clearInterval(timer)
    timer = setInterval(() => {
        count++;
        data.time = showNum(parseInt(count / 60 / 60)) + ':' + showNum(parseInt(count / 60) % 60) + ':' +
            showNum(
                count % 60)
    }, 1000)
}
function showNum(num) {
    if (num < 10) {
        return '0' + num
    }
    return num
}